package com.cy.chatTest.controller;


import com.cy.chatTest.ChatTestApplication;
import com.cy.chatTest.bin.BaseEntity;
import com.cy.chatTest.common.EmailSender;
import com.cy.chatTest.common.StringUtils;
import com.cy.chatTest.db.UserInfo;
import com.cy.chatTest.db.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/register")
public class Register {

    @Autowired
    UserInfoRepository userInfoRepository;

    @PostMapping("/emailRegister")
    public BaseEntity emailRegister(String email, String nickname, String password, String emailCode) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(emailCode)) {
            return new BaseEntity(false, "参数不能为空");
        } else if (!StringUtils.isEmail(email)) {
            return new BaseEntity(false, "请输入正确的邮箱地址");
        } else if (userInfoRepository.findByUsername(email) != null) {
            return new BaseEntity(false, "注册失败,该账号已存在");
        } else if (!emailCode.equals(ChatTestApplication.emailCodes.get(email))) {
            return new BaseEntity(false, "邮箱验证码错误");
        } else {
            try {
                ChatTestApplication.emailCodes.remove(email);
                UserInfo userInfo = new UserInfo(email, nickname,password);
                //新注册的设置默认头像
                userInfo.setImgUrl("head/default.jpg");
                userInfo = userInfoRepository.save(userInfo);

                return new BaseEntity(true, userInfo);
            } catch (Exception e) {
                return new BaseEntity(false, "注册失败");
            }
        }
    }

    @PostMapping("/getRegisterMailCode")
    public BaseEntity getRegisterMailCode(String email) {
        if (!StringUtils.isEmail(email)) {
            return new BaseEntity(false, "请输入正确的邮箱地址");
        } else if (userInfoRepository.findByUsername(email) != null) {
            return new BaseEntity(false, "注册失败,该账号已存在");
        } else {
            String code = (100000 + new Random().nextInt(899999)) + "";
            ChatTestApplication.emailCodes.put(email, code);
            try {
                EmailSender.sendEmail(email, "注册验证码", code);
                return new BaseEntity();
            } catch (Exception e) {
                return new BaseEntity(false, "邮箱验证码发送失败");
            }
        }

    }
}
